package com.kaifamiao.req;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;

@WebServlet( urlPatterns = "/file/upload" ,
             initParams = @WebInitParam( name = "position" , value = "D:/upload" ))
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    // 用来记录文件上传位置的字段
    private String position ;

    @Override
    public void init() throws ServletException {
        // HttpServlet类继承了GenericServlet类，
        // GenericServlet实现了Servlet接口和ServletConfig接口，
        // 因此可以通过 this.getInitParameter 直接获取初始化参数
        this.position = this.getInitParameter( "position" );
    }

    @Override
    protected void doGet(HttpServletRequest request , HttpServletResponse response ) throws ServletException, IOException {
        throw new IllegalStateException( "不支持用GET方式上传文件" );
    }

    @Override
    protected void doPost(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding( "UTF-8" );
        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html;charset=UTF-8" );

        PrintWriter out = response.getWriter();

        String componentName = "upfile" ;
        Part part = request.getPart( componentName );
        if( part == null ) {
            out.println( "<div>表单的enctype属性值不是multipart/form-data 或者 文件选择组件的名称不是 " + componentName + "</div>" );
            return ;
        }


        String filename = part.getSubmittedFileName(); // Servlet 3.1 ( Tomcat 7 不支持 )
        // 若 文件名不为 null 且 不是空串
        if( filename == null || filename.trim().isEmpty() ){
            out.println( "<div>请选择文件后再提交</div>" );
            return ;
        }

        int index = filename.lastIndexOf( "." );
        if( index == -1 ) {
            filename = filename + "-" + System.currentTimeMillis() ;
        } else {
            String prefix = filename.substring(0, index);
            String suffix = filename.substring(index);
            filename = prefix + "-" + System.currentTimeMillis() + suffix ;
        }

        // 获得用于读取已上传文件内容的字节输入流
        InputStream input = part.getInputStream();
        File target = new File( position , filename );
        OutputStream output = new FileOutputStream( target );

        int n ;
        byte[] buffer = new byte[ 1 << 20 ];
        while ( ( n = input.read( buffer ) ) != -1 ) {
            output.write( buffer , 0 , n );
        }

        output.close();
        input.close();

        out.println( "<div>文件" + filename + "上传成功</div>" );
        System.out.println( "上传成功" );
    }
}
